import React, { useEffect, useState } from 'react';
import { Tabs, message, Table, Button, List, Collapse, Descriptions } from 'antd';
import { ProList, ProTable } from '@ant-design/pro-components';
import { getCorpProjectUserList } from '@/services/public';
import FileOpen from '../FileIframOpen';
import RenderMoreFile from '../FileMoreRender';
import PermissionManage from '../PermissionManage';
import UploadLega from '../UploadLega';
import styles from './index.less';

const { TabPane } = Tabs;
const { Panel } = Collapse;
let pageNo = 1;

interface ProjectPersonInfoProps {
  projectInfo: any;
  defaultKey: '1' | '2' | '3' | '4';
  onChange: (key?: string) => any;
}

const ProjectPersonInfo: React.FC<ProjectPersonInfoProps> = ({ projectInfo, defaultKey, onChange}) => {
  const [showFile, setShowFile] = useState<boolean>(false);
  const [fileUrl, setFileUrl] = useState<string>('');
  const [operationKey, setOperationKey] = useState<'1' | '2' | '3' | '4' |'5'>(defaultKey || '2');
  const [total, setTotal] = useState<number>(0);
  const [loading, setLoading] = useState<boolean>(false);
  const [list, setList] = useState<any[]>([]);
  const [showB, setShowButton] = useState<boolean>(false);
  const [showLega, handleLega] = useState<boolean>(false);

  const owner: any[] = [
    {
      title: '建设单位',
      dataIndex: 'corpName',
    },
    {
      title: '劳动用工监管承诺书',
      dataIndex: 'workPromiseFileUrl',
      render: (_:any, record: any) => (
        <span>
          {record.workPromiseFileUrl ? (
            <a
              onClick={() => {
                setFileUrl(record.workPromiseFileUrl);
                setShowFile(true);
              }}
            >
              查看
            </a>
          ) : '-'}
        </span>
      ),
    },
    {
      title: '职务',
      dataIndex: 'post',
    },
    {
      title: '姓名',
      dataIndex: 'userName',
    },
    {
      title: '手机号',
      dataIndex: 'userPhone',
    },
    {
      title: '任命书',
      dataIndex: 'appointFileIdUrl',
      render: (_:any, record: any) => (
        <span>
          {record.appointFileIdUrl ? (
            <a
              onClick={() => {
                setFileUrl(record.appointFileIdUrl);
                setShowFile(true);
              }}
            >
              查看
            </a>
          ) : '-'}
        </span>
      ),
    },
  ];

  const builder: any[] = [
    {
      title: '施工单位',
      dataIndex: 'corpName',
    },
    {
      title: '职务',
      dataIndex: 'post',
    },
    {
      title: '劳动用工监管承诺书',
      dataIndex: 'workPromiseFileUrl',
      render: (_:any, record: any) => (
        <span>
          {record.workPromiseFileUrl ? (
            <a
              onClick={() => {
                setFileUrl(record.workPromiseFileUrl);
                setShowFile(true);
              }}
            >
              查看
            </a>
          ) : '-'}
        </span>
      ),
    },
    {
      title: '姓名',
      dataIndex: 'userName',
    },
    {
      title: '手机号',
      dataIndex: 'userPhone',
    },
    {
      title: '身份证',
      dataIndex: 'userCertNo',
    },
    {
      title: '任命书',
      dataIndex: 'appointFileIdUrl',
      render: (_:any, record:any) => {
        if (record.appointFileIdUrl) {
          return (
            <a
              onClick={() => {
                setFileUrl(record.appointFileIdUrl);
                setShowFile(true);
              }}
            >
              查看
            </a>
          );
        }
        return '-';
      },
    },
  ];

  const columnsUser: any[] = [
    {
      title: '姓名',
      dataIndex: 'userName',
    },
    {
      title: '手机号',
      dataIndex: 'userPhone',
    },
    {
      title: '身份证',
      dataIndex: 'userCertNo',
    },
    {
      title: '任命书',
      dataIndex: 'appointFileIdUrl',
      render: (_:any, record:any) => {
        if (record.appointFileIdUrl) {
          return (
            <a
              onClick={() => {
                setFileUrl(record.appointFileIdUrl);
                setShowFile(true);
              }}
            >
              查看
            </a>
          );
        }
        return '-';
      },
    },
  ];

  const columns: any[] = [
    {
      title: '劳务公司名称',
      dataIndex: 'corpName',
    },
    {
      title: '公司营业执照',
      dataIndex: 'businessLicenseUrl',
      render: (_:any, record:any) => {
        if (record.businessLicenseUrl) {
          return (
            <a
              onClick={() => {
                setFileUrl(record.businessLicenseUrl);
                setShowFile(true);
              }}
            >
              查看
            </a>
          );
        }
        return '-';
      },
    },
    {
      title: '班组名称',
      dataIndex: 'post',
    },
    {
      title: '负责人',
      dataIndex: 'userName',
    },
    {
      title: '手机号',
      dataIndex: 'userPhone',
    },
    {
      title: '劳务承包/分包协议',
      dataIndex: 'appointFileIdUrl',
      render: (_:any, record:any) => {
        if (record.appointFileIdUrl) {
          return (
            <a
              onClick={() => {
                setFileUrl(record.appointFileIdUrl);
                setShowFile(true);
              }}
            >
              查看
            </a>
          );
        }
        return '-';
      },
    },
  ];

  const columnsGroup: any[] = [
    {
      title: '班组名称',
      dataIndex: 'name',
      key: 'name',
      width: 100,
      align: 'center',
    },
    {
      title: '负责人',
      dataIndex: 'userName',
      key: 'userName',
      width: 100,
      align: 'center',
    },
    {
      title: '手机号',
      dataIndex: 'userPhone',
      key: 'userPhone',
      width: 120,
      align: 'center',
    },
  ];
  const columnsLabor:any[] = [
    {
      title: '监理单位',
      dataIndex: 'corpName',
    },
    {
      title: '职务',
      dataIndex: 'post',
    },
    {
      title: '姓名',
      dataIndex: 'userName',
    },
    {
      title: '身份证',
      dataIndex: 'userCertNo',
    },
    {
      title: '手机号',
      dataIndex: 'userPhone',
    },
    {
      title: '任命书',
      dataIndex: 'appointFileIdUrl',
      render: (_:any, record:any) => {
        if (record.appointFileIdUrl) {
          return (
            <a
              onClick={() => {
                setFileUrl(record.appointFileIdUrl);
                setShowFile(true);
              }}
            >
              查看
            </a>
          );
        }
        return '-';
      },
    },
    {
      title: '营业执照',
      dataIndex: 'businessLicenseUrl',
      render: (_:any, record:any) => {
        if (record.businessLicenseUrl) {
          return (
            <a
              onClick={() => {
                setFileUrl(record.businessLicenseUrl);
                setShowFile(true);
              }}
            >
              查看
            </a>
          );
        }
        return '-';
      },
    },

  ]

  const getTableList = async (params:any) => {
    const res = await getCorpProjectUserList({
      pageSize: params.pageSize,
      pageNo: params.current,
      projectId: projectInfo.projectId,
      currentCorpId: projectInfo.corpId,
      type: operationKey,
    });
    if (res && res.success) {
      if (operationKey == '4') {
        if (res.data && res.data.length <= 0) {
          setShowButton(true);
        }
      }
      return res;
    }
    return {};
  };

  const requsetList = async () => {
    setLoading(true);
    const par: any = {
      pageSize: 5,
      pageNo: pageNo,
      projectId: projectInfo.projectId,
      currentCorpId: projectInfo.corpId,
      type: operationKey,
    };
    const res = await getCorpProjectUserList(par);
    setLoading(false);
    if (res && res.success) {
      setList(res.data || []);
      setTotal(res.total);
    } else {
      message.error((res && res.errMsg) || '请求错误');
    }
  };

  const expectData = () => {
    const btn = document.createElement('a');
    btn.download = `${projectInfo.projectName || ''} 人员信息.xls`;
    btn.href = `/api/detail/exportCorpProjectUser?corpId=${projectInfo.corpId}&projectId=${projectInfo.projectId}`;
    document.body.appendChild(btn);
    btn.click();
    document.body.removeChild(btn);
  };

  const handleActiveTab = (key: any) => {
    setOperationKey(key);
  };

  useEffect(() => {
    if (operationKey == '3') {
      requsetList();
    }
  }, [operationKey]);

  const paginationProps = {
    showSizeChanger: false,
    showQuickJumper: false,
    pageSize: 5,
    total: total,
    current: pageNo,
    onChange: (page:any, pageSize:any) => {
      pageNo = page;
      requsetList();
    },
  };

  const ListContent = ({ data }: { data: any }) => (
    <div className={styles.listContent}>
      <div className={styles.listContentItem}>
        <span>劳动用工管理承诺书</span>
        <p>
          {data.workPromiseFileUrl ? (
            <a
              onClick={() => {
                setFileUrl(data.workPromiseFileUrl);
                setShowFile(true);
              }}
            >
              查看
            </a>
          ) : (
            '-'
          )}
        </p>
      </div>
      <div className={styles.listContentItem}>
        <span>企业营业执照</span>
        <p>
          {data.businessLicenseUrl ? (
            <a
              onClick={() => {
                setFileUrl(data.businessLicenseUrl);
                setShowFile(true);
              }}
            >
              查看
            </a>
          ) : (
            '-'
          )}
        </p>
      </div>
      <div className={styles.listContentItem}>
        <span>姓名</span>
        <p>{data.userName || '-'}</p>
      </div>
      <div className={styles.listContentItem}>
        <span>手机号</span>
        <p>{data.userPhone || '-'}</p>
      </div>
      <div className={styles.listContentItem}>
        <span>劳务承包/分包协议</span>
        <p>
          {data.appointFileIdUrl ? (
            <a
              onClick={() => {
                setFileUrl(data.appointFileIdUrl);
                setShowFile(true);
              }}
            >
              查看
            </a>
          ) : (
            '-'
          )}
        </p>
      </div>
      {}
    </div>
  );

  return (
    <div>
      <Button
        size={'small'}
        type={'primary'}
        style={{ position: 'absolute', right: '28px', zIndex: '2' }}
        onClick={expectData}
      >
        导出人员信息
      </Button>
      <Tabs
        defaultActiveKey="2"
        destroyInactiveTabPane={false}
        activeKey={operationKey}
        onChange={handleActiveTab}
      >
        <TabPane tab="建设单位" key="2">
          <ProTable
            rowKey="id"
            size={'small'}
            request={getTableList}
            columns={owner}
            search={false}
            options={false}
          />
        </TabPane>
        <TabPane tab="施工单位" key="1">
          <ProTable
            rowKey="id"
            size={'small'}
            request={getTableList}
            columns={builder}
            search={false}
            options={false}
          />
        </TabPane>
        <TabPane tab="监理单位" key="5">
          <ProTable
            rowKey="id"
            size={'small'}
            request={getTableList}
            columns={columnsLabor}
            search={false}
            options={false}
          />
        </TabPane>
        <TabPane tab="劳务公司" key="3">
          <ProList
            size={'small'}
            rowKey="id"
            loading={loading}
            pagination={paginationProps}
            dataSource={list}
            renderItem={(item) => (
              <Collapse
                bordered={false}
                destroyInactivePanel={true}
                style={{ borderBottom: '1px solid #e5e5e5' }}
                activeKey={[item.id]}
                defaultActiveKey={[item.id]}
              >
                <Panel
                  showArrow={false}
                  className={styles.collapsePanl}
                  header={
                    <List.Item className={styles.header}>
                      <List.Item.Meta title={item.corpName} description={item.corpCode} />
                      <ListContent data={item} />
                    </List.Item>
                  }
                  key={item.id}
                >
                  {item.groupList && item.groupList.length > 0 && (
                    <div style={{ border: '1px solid #ececec' }}>
                      <Table
                        columns={columnsGroup}
                        dataSource={item.groupList}
                        pagination={false}
                        size={'small'}
                      />
                    </div>
                  )}
                </Panel>
              </Collapse>
            )}
          />
        </TabPane>
        <TabPane tab="劳资专员" key="4">
          <ProTable
            rowKey="id"
            size={'small'}
            request={getTableList}
            columns={columnsUser}
            search={false}
            options={false}
          />
          {projectInfo.lzUserWarnNotifyFileUrl || projectInfo.lzUserWarnAmendFileUrl ? (
            <Descriptions title="法律文书">
              <Descriptions.Item label="调查询问通知书">
                <RenderMoreFile
                  title="调查询问通知书"
                  fielUrl={projectInfo.lzUserWarnNotifyFileUrl}
                />
              </Descriptions.Item>
              <Descriptions.Item label="改正指令书">
                <RenderMoreFile title="改正指令书" fielUrl={projectInfo.lzUserWarnAmendFileUrl} />
              </Descriptions.Item>
            </Descriptions>
          ) : null}
          {showB && (
            <div style={{ textAlign: 'center', marginTop: '20px' }}>
              <PermissionManage
                type="button"
                key="manager"
                onClick={() => {
                  handleLega(true);
                }}
                className={styles.action}
                text="下发法律文书"
                perm="OA_PROJECT_MANAGER_URGE"
              />
            </div>
          )}
        </TabPane>
      </Tabs>
      {/* {renderTableList()} */}
      {showFile && (
        <FileOpen
          fielUrl={fileUrl}
          modalVisible={showFile}
          onCancel={() => {
            setShowFile(false);
            setFileUrl('');
          }}
        />
      )}
      {showLega && (
        <UploadLega
          visible={showLega}
          info={projectInfo}
          businessType={3}
          cancel={() => {
            handleLega(false);
          }}
          onSubmit={() => {
            if (onChange) {
              onChange(operationKey)
            }
            handleLega(false);
          }}
        />
      )}
    </div>
  );
};

export default ProjectPersonInfo;
